<template>
  <a-modal
    title="增加菜单"
    class="edit-knowledge-modal"
    :width="800"
    :visible="visible"
    @ok="addMenu"
    @cancel="closeModal"
  >
    <div class="edit-knowledge-modal-li">
      <span class="edit-knowledge-modal-li-title">请选择级别：</span>
      <a-select v-model:value="menuFrom.menuType" style="width: 250px" placeholder="菜单级别">
        <a-select-option value="1">一级菜单</a-select-option>
        <a-select-option value="2">二级菜单</a-select-option>
      </a-select>
    </div>
    <div v-if="menuFrom.menuType === '2'" class="edit-knowledge-modal-li">
      <span class="edit-knowledge-modal-li-title">请选择父级：</span>
      <a-select v-model:value="menuFrom.parentId" style="width: 250px" placeholder="请选择父级菜单">
        <a-select-option v-for="item in menuList" :key="item.menuId">{{
          item.menuName
        }}</a-select-option>
      </a-select>
    </div>
    <div class="edit-knowledge-modal-li">
      <span class="edit-knowledge-modal-li-title">请输入名称：</span>
      <a-input v-model:value="menuFrom.menuName" placeholder="请输入名称" style="width: 250px" />
    </div>
  </a-modal>
</template>
<script lang="ts">
import { defineComponent, inject, reactive, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import common from '@/api/common'

interface menu {
  menuId: number
  menuName: string
  secondLevelMenus: Array<{ menuId: number; menuName: string }>
}

export default defineComponent({
  setup() {
    const visible = inject<any>('addMenuState')
    /**
     * 关闭窗口
     */
    const closeModal = inject<any>('closeAddMenuModal')
    const menuList = ref<Array<menu>>([])
    const menuFrom = reactive({ menuType: '', menuName: '', parentId: '0' })
    watch(visible, async (now) => {
      if (now) {
        const result = await common.getMenuAll()
        if (result.data && result.data.length > 0) {
          menuList.value = result.data
        }
      } else {
        // 清除表单数据
        menuFrom.menuType = ''
        menuFrom.menuName = ''
        menuFrom.parentId = '0'
      }
    })

    const addMenu = () => {
      common
        .addMenu(menuFrom)
        .then(() => {
          closeModal()
          message.success('添加成功')
          window.location.reload()
        })
        .catch((error) => {
          console.log(error)
        })
    }
    return { visible, closeModal, menuList, menuFrom, addMenu }
  }
})
</script>

<style lang="scss" scoped>
.edit-knowledge-modal {
  &-li {
    margin: 10px 0;
    display: flex;
    align-items: center;
    &-title {
      display: inline-block;
      width: 100px;
    }
  }
}
</style>
